package top.linyuxb.lycloud.gateway.starter.utils.config;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.linyuxb.lycloud.gateway.starter.dto.LyGatewayUserInfoDto;

import java.util.List;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/8/16 19:03
 * @Desc:
 */
public class LyGatewayWebMvcConfigurerUtil {

    public static WebMvcConfigurer buildWebMvcConfigurer(
            List<HandlerInterceptor> handlerInterceptors, List<HttpMessageConverter<?>> lyGatewayConverters) {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                if (CollectionUtils.isNotEmpty(handlerInterceptors)) {
                    for (HandlerInterceptor handlerInterceptor : handlerInterceptors) {
                        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
                    }
                }
            }

            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
                resolvers.add(
                        new HandlerMethodArgumentResolver() {
                            @Override
                            public boolean supportsParameter(MethodParameter parameter) {
                                return parameter.getParameterType().isAssignableFrom(LyGatewayUserInfoDto.class);
                            }

                            @Override
                            public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                                          NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
                                return webRequest.getAttribute("userInfo", NativeWebRequest.SCOPE_REQUEST);
                            }
                        }
                );
            }

            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                if(CollectionUtils.isNotEmpty(lyGatewayConverters)){
                    converters.addAll(lyGatewayConverters);
                }
                WebMvcConfigurer.super.extendMessageConverters(converters);
            }
        };
    }
}
